package com.bdqn.t330.ch09.controller;

import com.bdqn.t330.ch09.entity.User;
import com.bdqn.t330.ch09.servcie.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/dologin")
    public String dologin(String usrName, String usrPassword, Model model, HttpSession session) {
/*        List<User> list = userService.loginService(usrName, usrPassword);
        if (list.size() < 1) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else {
            if (!list.get(0).getUsrPassword().equals(usrPassword)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            } else {
                //User user = new User();
                //user.setUsrName(usrName);
                //user.getRole().setRoleName();
                session.setAttribute("user", list.get(0));
                return "main";
            }
        }*/
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            User user = (User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "main";
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //session.invalidate();
        session.removeAttribute("user");
        SecurityUtils.getSubject().logout();//Shiro 注销
        //return "login";
        return "redirect:login";
    }
}
